<template>
  <div class="max_box">
    <!-- 用于合成图片的隐藏canvas -->
    <canvas canvas-id="saveCanvas" style="position: absolute; left: -9999px; width: 375px; height: 812px" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>
    <view class="invite-record-btn" @click="naviToInvitRecord">邀请记录</view>
    <div style="width: 100%; display: flex; justify-content: center">
      <div class="canvas_class">
        <!-- 显示小程序码 -->
        <image v-if="miniProgramQrCode" :src="miniProgramQrCode" style="width: 100%; height: 100%"></image>
        <!-- 用于保存和分享的隐藏canvas -->
        <canvas id="qrcodes" canvas-id="qrcodes" style="width: 180px; height: 180px; visibility: hidden; position: fixed; left: -9999px"></canvas>
      </div>
    </div>
    <div style="width: 100%; position: absolute; bottom: 50px; display: flex; justify-content: center; align-items: center">
      <!--   <button
        style="width: 150px; height: 30px; border-radius: 10px; background-color: #3c9cff; margin-right: 20px; color: #fff; text-align: center; line-height: 30px"
        @click="saveToAlbum"
        :loading="saving"
      >
        {{ saving ? "保存中..." : "保存相册" }}
      </button> -->
      <button style="width: 150px; height: 30px; border-radius: 10px; background-color: #f9ae3d; margin-left: 20px; color: #fff; text-align: center; line-height: 30px" open-type="share">
        分 享
      </button>
    </div>
    <u-modal :show="showModal" title="邀请返利规则" confirmText="我已知晓" @confirm="(showModal = false), (qqqqqqq = true)" confirmColor="#ff1e0f">
      <view class="slot-content">
        <rich-text :nodes="content"></rich-text>
      </view>
    </u-modal>
  </div>
</template>

<script>
import QRCode from "../../utils/qrcode.js";
import { getDicts } from "../../utils/request_sh";
import { getQrcode } from "../../utils/request_api.js";
export default {
  data() {
    return {
      merID: "",
      qqqqqqq: false,
      saving: false, // 保存状态
      canvasWidth: 375, // 画布宽度
      canvasHeight: 812, // 画布高度
      backgroundImageUrl: "https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/09/25/22222_20250925092504A010.jpg",
      content: `<p><em style="font-style:normal;color:#000">1. 邀请新用户可立即获得现金补贴(1元-10元)</p>
         <p><em style="font-style:normal;color:#000">2. 您邀请用户消费购买水卡后，立即获得30元现金补贴。</p>
				          <p><em style="font-style:normal;color:#000">2. 您邀请用户消费后，可获得返利。返利比例为被邀请用户消费总额的4‰</p>

				         `,
      showModal: true,
      // 添加小程序码数据
      miniProgramQrCode: "",
      qrcodeDrawn: false, // 添加二维码绘制状态标志
      qrCodeUrl: "",
    };
  },
  onShareAppMessage(res) {
    console.log(res);
    return {
      title: "注册即得200补贴!",
      path: "/pages_h5/myCenter/index?shareId=" + uni.getStorageSync("uid"),
      // imageUrl: '/static/share.png'
    };
  },
  onShareTimeline() {
    return {
      title: "智享优圈",
      query: "id=123",
      imageUrl: "/pages_h5/myCenter/index?id=" + uni.getStorageSync("uid"),
    };
  },
  onLoad(option) {
    console.log(option);
    this.getZidian();
    /*     uni.showModal({
      title: "返利规则",
      content: "1. 邀请人与被邀请人可立即获得现金补贴(1元-10元)\u3000\u3000\u3000\t \n 2. 您邀请用户消费后，可获得返利。返利比例为被邀请用户消费总额的4‰",

      showCancel: false, // 不显示取消按钮
      // 确认按钮的文字自定义
      confirmText: "我已知晓",

      success: function (res) {
        if (res.confirm) {
        } else {
        }
      },
    }); */
    if (option.id) {
      var userInfo = uni.getStorageSync("userInfo");
      console.log(userInfo);
      console.log(userInfo.phone);
      if (userInfo.phone != undefined && userInfo.phone != "") {
        // uni.navigateTo({
        // 	url: '/pages_h5/myCenter/index'
        // })
      }
    }
  },
  mounted() {
    // 获取系统信息，设置画布尺寸
    this.getSystemInfo();

    var uid = uni.getStorageSync("uid");
  },
  methods: {
    getZidian() {
      getDicts("tgyj")
        .then((response) => {
          console.log("🚀 ~ getZidian ~ response:", response);
          this.merID = response.data[0].dictValue;
          this.getQrcodess();
        })
        .catch((error) => {
          console.error("获取字典数据失败:", error);
          // 出错时默认显示按钮
          this.$globalData.seeButton = true;
        });
    },
    getQrcodess() {
      var uid = uni.getStorageSync("uid");
      getQrcode({
        paramPath: "pages_h5/index/components/detail?merIDD=" + this.merID + "&yaoiqngID=" + uid + "&type=3",
      }).then((res) => {
        console.log("@@@@@@@@@@", res);
        this.miniProgramQrCode = "data:image/png;base64," + res.msg;
      });
    },
    /* 跳转邀请订单记录 */
    naviToInvitRecord() {
      uni.navigateTo({
        url: "/pages_h5/myCenter/components/recordList",
      });
    },
    // 获取系统信息，设置画布尺寸
    getSystemInfo() {
      const systemInfo = uni.getSystemInfoSync();
      this.canvasWidth = systemInfo.windowWidth || 375;
      this.canvasHeight = systemInfo.windowHeight || 812;
    },

    // 保存到相册的主方法
    async saveToAlbum() {
      if (this.saving) return; // 防止重复点击

      this.saving = true;

      try {
        // 1. 检查授权状态
        await this.checkWritePhotosAlbumAuth();

        // 2. 合成图片
        const tempFilePath = await this.createCompositeImage();

        // 3. 保存到相册
        await this.saveImageToPhotosAlbum(tempFilePath);

        // 4. 显示成功提示
        uni.showToast({
          title: "保存成功",
          icon: "success",
          duration: 2000,
        });
      } catch (error) {
        console.error("保存失败:", error);
        uni.showToast({
          title: error.message || "保存失败",
          icon: "none",
          duration: 2000,
        });
      } finally {
        this.saving = false;
      }
    },

    // 检查相册写入权限
    checkWritePhotosAlbumAuth() {
      return new Promise((resolve, reject) => {
        uni.getSetting({
          success: (res) => {
            if (res.authSetting["scope.writePhotosAlbum"]) {
              // 已授权
              resolve();
            } else if (res.authSetting["scope.writePhotosAlbum"] === false) {
              // 用户拒绝过，需要引导用户去设置页面
              uni.showModal({
                title: "提示",
                content: "需要您授权保存相册权限，请在设置中开启",
                confirmText: "去设置",
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    uni.openSetting({
                      success: (settingRes) => {
                        if (settingRes.authSetting["scope.writePhotosAlbum"]) {
                          resolve();
                        } else {
                          reject(new Error("未获得相册权限"));
                        }
                      },
                      fail: () => {
                        reject(new Error("打开设置失败"));
                      },
                    });
                  } else {
                    reject(new Error("用户取消授权"));
                  }
                },
              });
            } else {
              // 首次申请权限
              uni.authorize({
                scope: "scope.writePhotosAlbum",
                success: () => {
                  resolve();
                },
                fail: () => {
                  reject(new Error("获取相册权限失败"));
                },
              });
            }
          },
          fail: () => {
            reject(new Error("获取授权信息失败"));
          },
        });
      });
    },

    // 创建合成图片
    createCompositeImage() {
      return new Promise((resolve, reject) => {
        // 1. 先下载背景图片
        this.downloadBackgroundImage()
          .then((backgroundTempPath) => {
            const ctx = uni.createCanvasContext("saveCanvas", this);

            // 2. 绘制背景图片（使用临时文件路径）
            ctx.drawImage(backgroundTempPath, 0, 0, this.canvasWidth, this.canvasHeight);

            // 3. 等待背景图片绘制完成后，获取二维码并绘制
            setTimeout(() => {
              // 直接使用base64数据
              if (this.miniProgramQrCode) {
                // 计算二维码在合成图片中的位置（与原布局保持一致）
                const qrcodeX = (this.canvasWidth - 230) / 2; // 考虑边框和padding
                const qrcodeY = this.canvasHeight - 350; // 距离底部位置

                // 先绘制二维码背景（白色边框）
                ctx.setFillStyle("#ffffff");
                ctx.fillRect(qrcodeX, qrcodeY, 230, 230);

                // 绘制蓝色边框
                ctx.setStrokeStyle("#3C9CFF");
                ctx.setLineWidth(4);
                ctx.strokeRect(qrcodeX, qrcodeY, 230, 230);

                // 绘制二维码
                // 修改这里，使用回调函数确保绘制完成后再导出图片
                ctx.drawImage(this.miniProgramQrCode, qrcodeX + 15, qrcodeY + 15, 200, 200);
                ctx.draw(true, () => {
                  // 等待绘制完成后再导出图片
                  setTimeout(() => {
                    uni.canvasToTempFilePath(
                      {
                        canvasId: "saveCanvas",
                        success: (res) => {
                          resolve(res.tempFilePath);
                        },
                        fail: (error) => {
                          console.error("导出图片失败:", error);
                          reject(new Error("生成图片失败"));
                        },
                      },
                      this,
                    );
                  }, 300);
                });
              } else {
                reject(new Error("没有可用的二维码数据"));
              }
            }, 800);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 下载背景图片到临时文件
    downloadBackgroundImage() {
      return new Promise((resolve, reject) => {
        uni.downloadFile({
          url: this.backgroundImageUrl,
          success: (res) => {
            if (res.statusCode === 200) {
              console.log("背景图片下载成功:", res.tempFilePath);
              resolve(res.tempFilePath);
            } else {
              reject(new Error("背景图片下载失败"));
            }
          },
          fail: (error) => {
            console.error("背景图片下载失败:", error);
            reject(new Error("背景图片下载失败"));
          },
        });
      });
    },

    // 获取二维码临时图片
    getQRCodeTempImage() {
      return new Promise((resolve, reject) => {
        // 直接返回base64格式的二维码数据
        if (this.miniProgramQrCode) {
          resolve(this.miniProgramQrCode);
        } else {
          reject(new Error("没有可用的二维码数据"));
        }
      });
    },

    // 保存图片到相册
    saveImageToPhotosAlbum(tempFilePath) {
      return new Promise((resolve, reject) => {
        uni.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success: () => {
            resolve();
          },
          fail: (error) => {
            console.error("保存到相册失败:", error);
            reject(new Error("保存到相册失败"));
          },
        });
      });
    },
  },
};
</script>

<style>
page {
  width: 100%;
  height: 100%;
}

.max_box {
  width: 100%;
  height: 100%;
  background-image: url("https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/09/25/22222_20250925092504A010.jpg");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.canvas_class {
  position: absolute;
  bottom: 150px;
  padding: 15px;
  width: 180px;
  height: 180px;
  border: 2px solid #3c9cff;
  border-radius: 15px;
  background-color: #fff;
}
uni-modal__bd {
  text-align: left; /* 设置文本左对齐 */
  white-space: pre-wrap; /* 保留换行和空格 */
}
/* .canvas_classs {
		padding: 15px;
	} */
.invite-record-btn {
  position: absolute;
  top: 10rpx;
  right: 20rpx;
  width: 90px; /* 根据实际需要调整宽度 */
  height: 30px;
  border-radius: 15px; /* 使按钮看起来更圆润 */
  border: 1px solid #3c9cff;
  color: #fff;
  text-align: center;
  line-height: 30px;
  font-size: 16px; /* 添加字体大小 */
  padding: 0; /* 去除默认内边距 */
  margin: 0; /* 去除默认外边距 */
}
</style>
